package ch.elca.lol.puissance4;

import ch.elca.lol.puissance4.board.Board;
import ch.elca.lol.puissance4.board.FastImBoard;
import ch.elca.lol.puissance4.game.Game;
import ch.elca.lol.puissance4.game.PlayerLoader;
import ch.elca.lol.puissance4.player.Player;

public class AIPit {
	private final String class1;
	private final String class2;
	private final int rounds;
	
	private int win1 = 0;
	private int win2 = 0;
	private int stale = 0;
	
	private final String name1;
	private final String name2;
	
	public AIPit(String class1, String class2, int rounds) {
		this.class1 = class1;
		this.class2 = class2;
		this.rounds = rounds;
		
		Player p = PlayerLoader.loadPlayer(class1);
		Player q = PlayerLoader.loadPlayer(class2);
		
		name1 = p.toString();
		name2 = q.toString();
	}
	
	public void run() {
		for(int i = 0; i < rounds; i++) {
			int res = playGame(class1, class2);
			if(res == 0)
				stale++;
			else if(res == 1)
				win1++;
			else if(res == -1)
				win2++;
			
			res = playGame(class2, class1);
			if(res == 0)
				stale++;
			else if(res == 1)
				win2++;
			else if(res == -1)
				win1++;
		}
	}
	
	private int playGame(String c1, String c2) {
		Player p = PlayerLoader.loadPlayer(c1);
		Player q = PlayerLoader.loadPlayer(c2);

		Board b = new FastImBoard(7, 6);
		Game g = new Game(p, q, b);
		g.configure(false, 0);
		g.play();

		return g.getResult();
	}

	public String getResult() {
		String i = rounds+" rounds played: \n";
		String c1 = name1+"\t"+win1+"\t"+(100*win1/(win1+win2))+"%\t"+(100*win1/(win1+win2+stale))+"%\n";
		String c2 = name2+"\t"+win2+"\t"+(100*win2/(win1+win2))+"%\t"+(100*win2/(win1+win2+stale))+"%\n";
		String s = "Stale:\t"+stale+"\t\t"+(100*stale/(win1+win2+stale))+"%";
		return i+c1+c2+s;
	}
}
